<template>
  <view class="custom-calendar">
    <!-- 月份选择 -->
    <view class="calendar-header">
      <view class="month-picker" @click="toggleMonthPicker">
        <text style="font-weight: normal">{{ currentYear }}年{{ currentMonth + 1 }}月</text>
        <view class="arrow"></view>
      </view>
      <view v-if="showMonthPicker" class="month-list">
        <view
          v-for="(month, index) in months"
          :key="index"
          class="month-item"
          @click="selectMonth(index)"
        >
          <text>{{ month }}月</text>
        </view>
      </view>
    </view>

    <!-- 星期标题 -->
    <view class="weekdays">
      <text v-for="day in days" :key="day" class="weekday">{{ day }}</text>
    </view>

    <!-- 日期格子 -->
    <view class="dates">
      <view
        v-for="(date, index) in dates"
        :key="index"
        :class="['date', { marked: isMarked(date), current: isCurrentMonth(date), today: isToday(date) }]"
        @click="handleDateClick(date)"
      >
        <view class="date-text">
          <text class="date-number">{{ date.getDate() }}</text>
        </view>
      </view>
    </view>

    <!-- 图例 -->
    <view class="legend">
      <view class="legend-item">
        <view class="legend-color today-color"></view>
        <text>今日</text>
      </view>
      <view class="legend-item">
        <view class="legend-color marked-color"></view>
        <text>儿保</text>
      </view>
      <view class="legend-item">
        <view class="legend-color current-color"></view>
        <text>本月</text>
      </view>
    </view>

    <tn-modal v-model="show" :title="title" :content="content" :button="button" @click="clickBtn"></tn-modal>
  </view>
</template>

<script>
export default {
  props: {
    initialMarkedDates: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      days: ['日', '一', '二', '三', '四', '五', '六'], // 星期标题
      currentYear: new Date().getFullYear(), // 当前年份
      currentMonth: new Date().getMonth(), // 当前月份（0-11）
      localMarkedDates: [],  // 用于存储本地修改 
      months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // 月份列表
      showMonthPicker: false, // 是否显示月份选择下拉列表
      today: new Date(),// 当前日期
      show: false,
        title: '儿保提醒',
        content: '',
        button: [{
            text: '取消',
            backgroundColor: 'tn-bg-gray',
            fontColor: '#FFFFFF',
            shape: 'round'
          },
          {
            text: '确定',
            backgroundColor: 'tn-bg-indigo',
            fontColor: '#FFFFFF'
          }
        ],
      selectedDate: ''
    };
  },
  computed: {
    markedDates() {
      return [...this.initialMarkedDates, ...this.localMarkedDates];
    },
    // 生成当前月份的日期数组
    dates() {
      const dates = [];
      const firstDay = new Date(this.currentYear, this.currentMonth, 1);
      const lastDay = new Date(this.currentYear, this.currentMonth + 1, 0);
      const startDay = firstDay.getDay();

      // 填充上个月的日期
      for (let i = 0; i < startDay; i++) {
        const date = new Date(firstDay);
        date.setDate(firstDay.getDate() - (startDay - i));
        dates.push(date);
      }

      // 填充本月的日期
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(this.currentYear, this.currentMonth, i);
        dates.push(date);
      }

      // 填充下个月的日期
      const endDay = lastDay.getDay();
      for (let i = 1; i <= 6 - endDay; i++) {
        const date = new Date(lastDay);
        date.setDate(lastDay.getDate() + i);
        dates.push(date);
      }

      return dates;
    }
  },
  methods: {
    // 切换月份选择下拉列表的显示状态
    toggleMonthPicker() {
      this.showMonthPicker = !this.showMonthPicker;
    },
    // 选择月份
    selectMonth(monthIndex) {
      this.currentMonth = monthIndex; // 更新当前月份
      this.showMonthPicker = false; // 关闭下拉列表
    },
    // 处理日期点击事件
    handleDateClick(date) {
      const dateStr = this.formatDate(date);
      const selectedDate = new Date(dateStr);
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      if (selectedDate < today){
        return;
      }

      this.selectedDate = dateStr;
      if (this.isMarked(date)) {
        this.unmarkDate(dateStr);
      } else {
        this.show = true;
        this.content = `设置 ${dateStr} 为儿保提醒(邮件通知)`;
      }
    },
    // 标记日期
    markDate(dateStr) {
      if (!this.markedDates.includes(dateStr)) {
        this.localMarkedDates.push(dateStr);
      }
    },
    // 取消标记日期
    unmarkDate(dateStr) {
       // Compare only the date part
      if (this.markedDates.includes(dateStr)) {
        this.$emit('update-marked-dates', this.selectedDate);
      }
      
    },
    // 判断日期是否被标记
    isMarked(date) {
      if (!date) return false;
      // 将日期对象转换为与后端相同格式的字符串进行比较
      const dateStr = this.formatDate(date);
      return this.markedDates.includes(dateStr);
    },
    // 判断日期是否属于当前月份
    isCurrentMonth(date) {
      return date.getMonth() === this.currentMonth;
    },
    // 判断日期是否为今日
    isToday(date) {
      return (
        date.getFullYear() === this.today.getFullYear() &&
        date.getMonth() === this.today.getMonth() &&
        date.getDate() === this.today.getDate()
      );
    },
    // 点击按钮
    clickBtn(event) {
      if (event.index == 1) {
        this.$emit('update-marked-dates', this.selectedDate);
      }
      this.show = false;
    },
    formatDate(date) {
      // 使用本地时间，确保日期格式与后端一致
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.custom-calendar {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px; /* 添加底部间距 */
}

.calendar-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  font-size: 18px;
  font-weight: bold;
  position: relative;
}

.month-picker {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.arrow {
  margin-left: 8px;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 6px solid #666; /* 调整颜色 */
  transition: transform 0.2s ease; /* 添加动画效果 */
}

.month-picker.active .arrow {
  transform: rotate(180deg); /* 点击时旋转箭头 */
}

.month-list {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
  width: 120px;
  max-height: 200px;
  overflow-y: auto;
}

.month-item {
  padding: 10px;
  text-align: center;
  cursor: pointer;
}

.month-item:hover {
  background-color: #f5f5f5;
}

.weekdays {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  font-size: 16px;
  color: #666;
}

.dates {
  display: flex;
  flex-wrap: wrap;
}

.date {
  width: 14%;
  text-align: center;
  padding: 8px 0;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px; /* 减小高度 */
}

.date-text {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.date-number {
  font-size: 14px;
}

.date.marked .date-number {
  color: #fff;
}

.date.current .date-number {
  color: #000;
}

.date:not(.current) .date-number {
  color: #ccc;
}

.date.today .date-text {
  background-color: #f0f0f0; /* 今日日期灰色背景 */
  border-radius: 50%; /* 圆形 */
  width: 35px; /* 调整宽度 */
  height: 35px; /* 调整高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.mark-label {
  font-size: 12px;
  margin-top: 4px;
  color: inherit; /* 继承父元素颜色 */
}

.date.marked .date-text {
  background-color: #ffa500; /* 橘黄色 */
  border-radius: 50%; /* 圆形 */
  width: 35px; /* 调整宽度 */
  height: 35px; /* 调整高度 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.legend {
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  margin-top: 20px;
  margin-left: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 8px;
}

.today-color {
  background-color: #f0f0f0;
}

.marked-color {
  background-color: #ffa500;
}

.current-color {
  background-color: #000;
}
</style>